import Vue from 'vue'
import Vuex from 'vuex'
import {login} from '../api/api'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: ''
  },
  getters: {
    token(state) {
      return state.token
    }
  },
  mutations: {
    SET_TOKEN(state,token) {
      state.token = token
    }
  },
  actions: {
    setToken({ commit,state }) {
      return new Promise(resolve => {
        if (!state.token || state.token.time < new Date().getTime) {
          login().then(res => {
            commit('SET_TOKEN',{
              token:res.data.message,
              time:new Date().getTime() + 2 * 60 * 60 * 1000
            })
            resolve()
          })
        }else {
          resolve()
        }
      })
    }
  },
  modules: {
  }
})
